package com.weng.platform.stories.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.framework.common.model.component.tree.TreeGridBuilder;
import com.weng.framework.common.model.component.tree.TreeNode;
import com.weng.framework.core.exception.GlobalServiceException;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.dao.mybatis.model.page.PageModel;
import com.weng.framework.dao.mybatis.service.BaseServiceImpl;
import com.weng.platform.stories.entity.Iterations;
import com.weng.platform.stories.entity.Stories;
import com.weng.platform.stories.mapper.IterationsMapper;
import com.weng.platform.stories.mapper.StoriesMapper;
import com.weng.platform.stories.model.dto.LessonPeriodRelUserDto;
import com.weng.platform.stories.model.vo.StoriesTreeNode;
import com.weng.platform.stories.service.IStoriesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;


/**
 * 课时 服务实现类
 *
 * @author wenghui
 * @date 2020-05-17 13:16:39
 *
 */ 
@Slf4j
@Service
public class StoriesServiceImpl extends BaseServiceImpl<StoriesMapper, Stories> implements IStoriesService {
	@Autowired
	private StoriesMapper storiesMapper;
    @Autowired
    private IterationsMapper iterationsMapper;


    public List<StoriesTreeNode> getTreeGridData(String name, String iterationId, String[] chapterTypes, String parentId, String isExpand){
        Stories queryObj = new Stories();
        QueryWrapper<Stories> wrapper = new QueryWrapper<>(queryObj);
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name", name);
        }
        if(!StringUtils.isEmpty(iterationId)){
            wrapper.eq("iteration_id", iterationId);
        }
        if(chapterTypes != null && chapterTypes.length != 0 ){
            boolean isAll = false;
            for(String type : chapterTypes){
                if(StringUtils.isEmpty(type)){
                    isAll = true;
                }
            }
            // 如果是没有查询全部，则加上查询条件
            if(!isAll){
                wrapper.in("chapter_type", chapterTypes);

            }
        }

        List<Stories> data = storiesMapper.selectList(wrapper);
        List<StoriesTreeNode> list = new TreeGridBuilder<Stories, StoriesTreeNode>(data)
                .build(new LessonPeriodComparator(),new StoriesTreeNode(), false);
        if ("1".equals(isExpand)) {
            TreeNode.expandAllNodes(list);
        }
        TreeNode.expandNodesByDepth(list,2);
        return list;
    }



    private class LessonPeriodComparator implements Comparator<Stories> {
        @Override
        public int compare(Stories o1, Stories o2) {
            Integer depth1 = o1.getPosition();
            Integer depth2 = o2.getPosition();
            if(depth1==null || depth2==null){
                return 0;
            }else {
                return o1.getPosition().intValue() - o2.getPosition().intValue();
            }
        }
    }

    private class LessonPeriodRelUserComparator implements Comparator<LessonPeriodRelUserDto> {
        @Override
        public int compare(LessonPeriodRelUserDto o1, LessonPeriodRelUserDto o2) {
            Integer depth1 = o1.getPosition();
            Integer depth2 = o2.getPosition();
            if(depth1==null || depth2==null){
                return 0;
            }else {
                return o1.getPosition().intValue() - o2.getPosition().intValue();
            }
        }
    }

	/**
	 * 分页查询课时
	 * @return
	 */
	@Override
	public IPage<Stories> list(Integer pageNo, Integer pageSize) {
		QueryWrapper<Stories> qw = new QueryWrapper<Stories>();
		IPage<Stories> page = new PageModel<Stories>(pageNo,pageSize);
		return storiesMapper.selectPage(page,qw);
	}

	/**
	 * 获取单个课时
	 * @param id
	 * @return
	 */
	@Override
	public Stories getById(Serializable id) {
		return super.getById(id);
	}

	private boolean isCoursePublish(String courseId){
	    if(StringUtils.isNotEmpty(courseId)){
            Iterations iterations = this.iterationsMapper.selectById(courseId);
        }
        return false;
    }
	/**
	 * 新增单个课时
	 * @param stories
	 * @return
	 */
	@Override
	public ResponseData add(Stories stories) throws GlobalServiceException {
		storiesMapper.insert(stories);
		return ResponseData.success();
	}

	/**
	 * 更新单个课时
	 * @param stories
	 * @return
	 * @throws GlobalServiceException
	 */
	@Override
	public ResponseData update(Stories stories) throws GlobalServiceException {

        storiesMapper.updateById(stories);
        return ResponseData.success();
	}

	@Override
	public ResponseData removeByIds(String ids) {
		String[] lessonPeriodIds = ids.split(",");
		for(String id : lessonPeriodIds){
            List<Stories> storiesChildren = getByParentId(id);
		    if(StringUtils.isNotEmpty(id) &&  storiesChildren != null && storiesChildren.size() > 0){
                String[] lessonPeriodIdsTemp = ids.split(",");
                for(String idTemp : lessonPeriodIdsTemp){
                    boolean isContains = false;
                    for(Stories storiesChild : storiesChildren){

                    }
                }
                for(Stories storiesChild : storiesChildren){
                    boolean isContains = false;
                    for(String idTemp : lessonPeriodIdsTemp){
                        if(idTemp.equalsIgnoreCase(storiesChild.getId())){
                            isContains = true;
                            break;
                        }
                    }
                    // 如果该结点下某个子结点，没有在这次一起删除，就删除失败
                    if(!isContains){
                        Stories stories = storiesMapper.selectById(id);
                        if(stories !=null){
                            return ResponseData.failed(stories.getName()+ "  有子节点: "+ storiesChild.getName()
                                    +" ，不能删除，请先删除子节点，才能删除父结点!");
                        }
                    }
                }
            }
        }
		this.removeByIds(Arrays.asList(lessonPeriodIds));
        return ResponseData.success();
	}

	private List<Stories> getByParentId(String parentId){
	    QueryWrapper<Stories> qw = new QueryWrapper<>();
        qw.eq("parent_id", parentId);
        return  storiesMapper.selectList(qw);
    }

}
